<script lang="ts" setup>
import { ArrowDownBold } from '@element-plus/icons-vue'
import { listen, UnlistenFn } from '@tauri-apps/api/event'
import { WebviewWindow } from '@tauri-apps/api/webviewWindow'
import { open as openDialog } from '@tauri-apps/plugin-dialog'
import { remove, rename } from '@tauri-apps/plugin-fs'
import { openPath } from '@tauri-apps/plugin-opener'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import { computed, onMounted, onUnmounted, ref } from 'vue'
import Logo from '../components/Logo.vue'
import SettingsDialog from '../components/SettingsDialog.vue'
import { FileItem, useTagStore2 } from '../stores/tag'
import {
  cvsAdd,
  cvsCommit,
  cvsCommitSmart,
  cvsHistory,
  cvsPreCommitCheck,
  CVSStatus,
  cvsTag,
  cvsTagMulti,
  cvsUpdate,
  cvsRemoveTag
} from '../utils/cvs'
import { openFileFolder } from '../utils/file'
import { buildHistoryVersionKey, getCachedHistory, setCachedHistory } from '../utils/historyCache'

const tagStore = useTagStore2()

const getFileVersionKey = (file: FileItem) => buildHistoryVersionKey(file.workingVersion, file.repositoryVersion)

interface HistoryCacheOptions {
  updateLoadingText?: (text: string) => void
  onHistoryError?: (file: FileItem, error: unknown) => void
}

const fetchHistoriesWithCache = async (
  files: FileItem[],
  options?: HistoryCacheOptions
): Promise<Map<string, string>> => {
  const historyMap = new Map<string, string>()
  const cacheResults = await Promise.all(
    files.map(async (file) => {
      const versionKey = getFileVersionKey(file)
      const cachedHistory = await getCachedHistory(file.path, versionKey)
      return { file, versionKey, cachedHistory }
    })
  )

  const pendingFiles = cacheResults.filter(({ cachedHistory }) => !cachedHistory)
  cacheResults.forEach(({ file, cachedHistory }) => {
    if (cachedHistory) {
      historyMap.set(file.path, cachedHistory.trim())
    }
  })

  if (pendingFiles.length > 0) {
    options?.updateLoadingText?.('导出清单...')
  }
  for (const { file, versionKey } of pendingFiles) {
    try {
      options?.updateLoadingText?.(`导出文件: ${file.name}...`)
      const history = (await cvsHistory(file.path)).trim()
      historyMap.set(file.path, history)
      if (versionKey) {
        await setCachedHistory(file.path, versionKey, history)
      }
    } catch (error) {
      console.error(`导出文件 ${file.name} 清单失败:`, error)
      options?.onHistoryError?.(file, error)
    }
  }

  return historyMap
}

const historyDialogVisible = ref(false)
const histories = ref('')

const settingsDialogVisible = ref(false)

let dragListener: UnlistenFn | undefined = undefined

const selectTag = (tagName: string) => {
  tagStore.currentTagName = tagName
}

onMounted(async () => {
  dragListener = await listen('tauri://drag-drop', async (event) => {
    const payload = event.payload as any
    const files: string[] = [...new Set<string>(payload.paths)]
    await tagStore.addFiles(files)
  })
})

onUnmounted(() => {
  if (dragListener) {
    dragListener()
  }
})

const openDiffPage = (file: FileItem) => {
  new WebviewWindow('diff', {
    url: '/diff?file=' + encodeURIComponent(file.path) + '&tag=' + encodeURIComponent(file.baseVersionTag!),
    title: `Diff: ${file.name}`,
    width: 1100,
    height: 700,
    resizable: true,
    center: true,
    focus: true,
    alwaysOnTop: false
  })
}

const addNewTag = async () => {
  // noinspection JSUnusedGlobalSymbols
  const { value: tagName } = await ElMessageBox.prompt('请输入新TAG名称', '新增TAG', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPattern: /\S+/,
    inputErrorMessage: 'TAG名称不能为空',
    beforeClose: (action, instance, done) => {
      if (action === 'confirm') {
        const inputValue = instance.inputValue
        if (!/^[a-zA-Z]/.test(inputValue)) {
          ElMessage.error('TAG必须以字母开头')
          return
        }
        if (tagStore.tags.some((tag) => tag.name === inputValue)) {
          ElMessage.error('TAG已存在')
          return false
        }
      }
      done()
    }
  })
  tagStore.addTag(tagName)
  ElMessage({
    type: 'success',
    message: `新增TAG: ${tagName}`
  })
}

const deleteTag = async (tagName: string, event: Event) => {
  event.stopPropagation()
  await ElMessageBox.confirm(`确定要删除TAG ${tagName} 吗？`, '删除确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
  await tagStore.removeTag(tagName)
  ElMessage({ type: 'success', message: '删除成功' })
}

const addFile = async () => {
  if (!tagStore.currentTagName) {
    ElMessage.warning('请先选择一个TAG')
    return
  }
  try {
    const selected = await openDialog({
      multiple: true,
      filters: [
        {
          name: '所有文件',
          extensions: ['*']
        }
      ]
    })
    if (selected) {
      const files = Array.isArray(selected) ? selected : [selected]
      await tagStore.addFiles(files)
    }
  } catch (err) {
    console.error('选择文件出错:', err)
    ElMessage.error('选择文件失败')
  }
}

const updateAllStatus = async () => {
  const targetFiles = tagStore.currentTagFiles.filter((file) => file.selected)
  if (!targetFiles || targetFiles.length === 0) {
    ElMessage.warning('请先选择文件')
    return
  }
  await tagStore.updateSelectedFilesStatus()
}

const commitAndTag = async () => {
  const tagName = tagStore.currentTagName
  if (!tagName) {
    ElMessage.warning('请先选择TAG')
    return
  }
  const currentFiles = tagStore.currentTagFiles.filter((file) => file.selected)
  if (currentFiles.length === 0) {
    ElMessage.warning('请先选择文件')
    return
  }
  const loadingInstance = ElLoading.service({
    lock: true,
    text: '更新文件状态...',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  try {
    await tagStore.updateSelectedFilesStatus()
    loadingInstance.setText('提交文件...')
    for (const file of currentFiles) {
      try {
        console.log(`提交文件: ${file.path}`)
        loadingInstance.setText(`检查文件状态: ${file.name}`)

        // 预提交检查
        const checkResult = await cvsPreCommitCheck(file.path)
        console.log(`文件 ${file.name} 状态检查结果:`, checkResult)

        if (checkResult.status.rawStatus === CVSStatus.UpToDate) {
          console.log(`文件 ${file.name} 已是最新版本，跳过提交`)
          continue
        }

        loadingInstance.setText(`处理文件: ${file.name}`)

        if (checkResult.status.rawStatus === CVSStatus.Unknown) {
          console.log(`添加新文件到CVS: ${file.name}`)
          await cvsAdd(file.path)
        } else if (
          checkResult.status.rawStatus === CVSStatus.Conflict ||
          checkResult.status.rawStatus === CVSStatus.UnresolvedConflict ||
          checkResult.status.rawStatus === CVSStatus.NeedsCheckout ||
          checkResult.status.rawStatus === CVSStatus.NeedsMerge
        ) {
          console.log(`处理需要合并的文件: ${file.name}`)
          // 备份当前文件
          await rename(file.path, file.path + '.bak')
          // 更新到最新版本
          await cvsUpdate(file.path)
          // 删除更新后的文件
          await remove(file.path)
          // 恢复本地修改的文件
          await rename(file.path + '.bak', file.path)
          console.log(`文件 ${file.name} 已准备好进行手动合并`)
        } else if (
          checkResult.status.rawStatus === CVSStatus.Added ||
          checkResult.status.rawStatus === CVSStatus.LocallyAdded
        ) {
          console.log(`文件 ${file.name} 已添加到CVS，准备提交`)
          // LocallyAdded状态的文件已经添加到CVS，可以直接提交
        }

        loadingInstance.setText(`提交文件: ${file.name}`)
        await cvsCommitSmart(file.path, tagName, true)
        console.log(`文件 ${file.name} 提交成功`)
      } catch (e) {
        console.error('提交文件出错:', e)
        const errorMsg = e instanceof Error ? e.message : String(e)

        // 提供更详细的错误信息
        if (errorMsg.includes('Up-to-date check failed')) {
          ElMessage.error(`文件 ${file.name} 需要更新后才能提交。建议：先执行CVS更新操作`)
        } else if (errorMsg.includes('需要合并') || errorMsg.includes('merge')) {
          ElMessage.error(`文件 ${file.name} 需要合并。建议：先更新文件，然后手动解决冲突后再提交`)
        } else if (errorMsg.includes('conflict') || errorMsg.includes('冲突')) {
          ElMessage.error(`文件 ${file.name} 存在冲突，请先解决冲突后再提交`)
        } else if (errorMsg.includes('合并过程中发现冲突')) {
          ElMessage.error(`文件 ${file.name} 自动合并失败，存在冲突需要手动解决`)
        } else {
          ElMessage.error(`提交文件 ${file.name} 失败: ${errorMsg}`)
        }
        return
      }
    }
    loadingInstance.setText('TAGGING...')
    const paths = currentFiles.map((file) => file.path)
    try {
      await cvsTagMulti(paths, tagName)
    } catch (e) {
      console.error('打TAG出错:', e)
      ElMessage.error(`打TAG ${tagName} 失败`)
      return
    }
    await tagStore.updateSelectedFilesStatus()
    const historyMap = await fetchHistoriesWithCache(currentFiles, {
      updateLoadingText: (text: string) => loadingInstance.setText(text),
      onHistoryError: (file) => ElMessage.error(`导出文件 ${file.name} 清单失败`)
    })

    const orderedHistories = currentFiles
      .map((file) => historyMap.get(file.path))
      .filter((history): history is string => !!history && history.trim())

    if (orderedHistories.length === 0) {
      ElMessage.error('所有文件清单导出失败')
      return
    }

    histories.value = orderedHistories.map((history) => history.trim()).join('\n').trim()
    historyDialogVisible.value = true
  } finally {
    loadingInstance.close()
  }
  tagStore.updateTagUpdateTime()
}

const removeFile = async (row: FileItem) => {
  const confirmAction = await ElMessageBox.confirm(`确定要移除该文件吗？`, '移除确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => 'confirm')
    .catch((action) => action)

  if (confirmAction !== 'confirm') {
    return
  }

  const currentTag = tagStore.currentTagName
  const hasCurrentTag =
    !!currentTag && row.statusSnapshot?.tags?.some((tag) => tag.name === currentTag)

  let shouldRemoveTag = false
  if (hasCurrentTag) {
    const tagAction = await ElMessageBox.confirm(
      `该文件已存在当前TAG ${currentTag}，是否同步删除TAG？`,
      '同步删除TAG',
      {
        confirmButtonText: '删除TAG',
        cancelButtonText: '保留TAG',
        type: 'warning',
        distinguishCancelAndClose: true
      }
    )
      .then(() => 'confirm')
      .catch((action) => action)

    if (tagAction === 'close') {
      return
    }
    shouldRemoveTag = tagAction === 'confirm'
  }

  await tagStore.removeFile(row.path)
  ElMessage({
    type: 'success',
    message: '文件已移除'
  })

  if (shouldRemoveTag && currentTag) {
    try {
      await cvsRemoveTag(row.path, currentTag)
      ElMessage({
        type: 'success',
        message: `已同步删除TAG ${currentTag}`
      })
    } catch (error) {
      console.error('删除TAG失败:', error)
      ElMessage.error(`同步删除TAG失败: ${error}`)
    }
  }
}

const openFile = (row: FileItem) => {
  openPath(row.path)
}

const copyHistory = () => {
  navigator.clipboard
    .writeText(histories.value)
    .then(() => {
      ElMessage({
        type: 'success',
        message: '已复制到剪切板'
      })
    })
    .catch((err) => {
      console.error('复制失败:', err)
      ElMessage.error('复制失败')
    })
} //TODO 本地旧版本且未修改  线上有更新的版本

const commitAndTagSingle = async (file: FileItem) => {
  const tagName = tagStore.currentTagName
  if (!tagName) {
    ElMessage.warning('请先选择TAG')
    return
  }

  const loadingInstance = ElLoading.service({
    lock: true,
    text: '更新文件状态...',
    background: 'rgba(0, 0, 0, 0.7)'
  })

  try {
    await tagStore.updateCvsStatus(file)

    loadingInstance.setText('提交文件...')
    try {
      console.log(`提交文件: ${file.path}`)
      if (file.rawStatus === CVSStatus.UpToDate) {
        // 已是最新状态，无需提交
      } else if (file.rawStatus === CVSStatus.Unknown) {
        await cvsAdd(file.path)
      } else if (
        file.rawStatus === CVSStatus.Conflict ||
        file.rawStatus === CVSStatus.UnresolvedConflict ||
        file.rawStatus === CVSStatus.NeedsCheckout
      ) {
        await rename(file.path, file.path + '.bak')
        await cvsUpdate(file.path)
        await remove(file.path)
        await rename(file.path + '.bak', file.path)
      }
      await cvsCommit(file.path, tagName)
    } catch (e) {
      console.error('提交文件出错:', e)
      ElMessage.error(`提交文件 ${file.name} 失败`)
      return
    }

    loadingInstance.setText('TAGGING...')
    try {
      await cvsTag(file.path, tagName)
    } catch (e) {
      console.error('打TAG出错:', e)
      ElMessage.error(`打TAG ${tagName} 失败`)
      return
    }
    await tagStore.updateCvsStatus(file)

    loadingInstance.setText('导出清单...')
    try {
      const history = await cvsHistory(file.path)
      histories.value = history.trim()
      historyDialogVisible.value = true
    } catch (e) {
      console.error('导出清单出错:', e)
      ElMessage.error(`导出清单 ${file.name} 失败`)
      return
    }

    ElMessage.success('操作成功完成')
  } finally {
    loadingInstance.close()
  }
}

const exportList = async () => {
  const tagName = tagStore.currentTagName
  if (!tagName) {
    ElMessage.warning('请先选择TAG')
    return
  }
  const currentFiles = tagStore.currentTagFiles.filter((file) => file.selected)
  if (currentFiles.length === 0) {
    ElMessage.warning('请先选择文件')
    return
  }
  const loadingInstance = ElLoading.service({
    lock: true,
    text: '获取最新状态...',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  try {
    await tagStore.updateSelectedFilesStatus()
    for (const file of currentFiles) {
      if (file.rawStatus === CVSStatus.Unknown) {
        ElMessage.warning(`${file.name}未提交，请先提交或取消勾选`)
        return
      } else if (file.rawStatus === 'Error' || file.rawStatus === 'Not-CVS-File') {
        ElMessage.warning(`${file.name}状态为'${file.status}'，请先处理`)
        return
      }
    }

    const historyMap = await fetchHistoriesWithCache(currentFiles, {
      updateLoadingText: (text: string) => loadingInstance.setText(text),
      onHistoryError: (file) => ElMessage.error(`导出文件 ${file.name} 清单失败`)
    })

    const orderedHistories = currentFiles
      .map((file) => historyMap.get(file.path))
      .filter((history): history is string => !!history && history.trim())

    if (orderedHistories.length === 0) {
      ElMessage.error('所有文件清单导出失败')
      return
    }

    histories.value = orderedHistories.map((history) => history.trim()).join('\n').trim()
    historyDialogVisible.value = true
  } finally {
    loadingInstance.close()
  }
  tagStore.updateTagUpdateTime()
}

const exportListSingle = async (file: FileItem) => {
  const tagName = tagStore.currentTagName
  if (!tagName) {
    ElMessage.warning('请先选择TAG')
    return
  }

  await tagStore.updateCvsStatus(file)
  if (file.rawStatus === CVSStatus.Unknown) {
    ElMessage.warning(`${file.name}未提交，请先提交`)
    return
  } else if (file.rawStatus === 'Error') {
    ElMessage.warning(`${file.name}错误，请先处理`)
    return
  }

  const loadingInstance = ElLoading.service({
    lock: true,
    text: '导出清单...',
    background: 'rgba(0, 0, 0, 0.7)'
  })

  try {
    await cvsTag(file.path, tagName)
    const historyMap = await fetchHistoriesWithCache([file], {
      updateLoadingText: (text: string) => loadingInstance.setText(text),
      onHistoryError: () => ElMessage.error(`导出文件 ${file.name} 清单失败`)
    })
    const history = historyMap.get(file.path)
    if (!history) {
      ElMessage.error(`导出清单 ${file.name} 失败`)
      return
    }
    histories.value = history.trim()
    historyDialogVisible.value = true
  } catch (e) {
    console.error('导出清单出错:', e)
    ElMessage.error(`操作失败: ${e}`)
  } finally {
    loadingInstance.close()
  }
  tagStore.updateTagUpdateTime()
}

const openFolder = (row: FileItem) => {
  openFileFolder(row.path)
}

const sortColumn = ref('name')
const sortDirection = ref('asc')

const sortByColumn = (column: string) => {
  if (sortColumn.value === column) {
    // 切换排序方向
    sortDirection.value = sortDirection.value === 'asc' ? 'desc' : 'asc'
  } else {
    sortColumn.value = column
    sortDirection.value = 'asc'
  }
}

const sortedFiles = computed(() => {
  if (!tagStore.currentTagFiles) return []

  return [...tagStore.currentTagFiles].sort((a, b) => {
    if (sortColumn.value === 'name') {
      const comparison = a.name.localeCompare(b.name)
      return sortDirection.value === 'asc' ? comparison : -comparison
    }
    return 0
  })
})

const isRowSelected = (row: FileItem) => {
  return row.selected
}

const toggleRowSelection = (row: FileItem) => {
  console.log(`Row ${row.name} selected: ${row.selected}`)
  tagStore.saveFileSelection()
}

const isAllSelected = computed(() => {
  return tagStore.currentTagFiles.length > 0 && tagStore.currentTagFiles.every((row) => row.selected)
})

const isIndeterminate = computed(() => {
  const selectedCount = tagStore.currentTagFiles.filter((row) => row.selected).length
  return selectedCount > 0 && selectedCount < tagStore.currentTagFiles.length
})

const toggleSelectAll = () => {
  const shouldSelect = !isAllSelected.value
  tagStore.currentTagFiles.forEach((row) => {
    row.selected = shouldSelect
  })
  tagStore.saveFileSelection()
}
</script>

<template>
  <div class="flex flex-row bg-[#F0F0F0] h-screen">
    <div class="flex flex-col mr-2 h-full w-70">
      <Logo class="h-[56px]" name="CvsTool" />
      <div class="px-2 w-full mb-4">
        <el-button class="w-full !h-11 !rounded-lg button-add-tag" type="primary" @click="addNewTag">新增TAG</el-button>
      </div>
      <div class="w-full px-2 overflow-auto select-none">
        <div v-if="tagStore.tagGroups.length === 0" class="py-4 text-center text-gray-500">暂无TAG</div>
        <div v-for="tagItem in tagStore.tagGroups" v-else :key="tagItem.reqNumber" class="py-1.5">
          <div class="flex flex-row items-center font-bold ml-2">{{ tagItem.reqNumber }}</div>
          <div
            v-for="tag in tagItem.tags"
            :key="tag.name"
            :class="{ 'tag-selected': tagStore.currentTagName === tag.name }"
            class="tag-entry flex flex-row items-center py-1 px-2 my-1 rounded cursor-pointer relative"
            @click="selectTag(tag.name)"
          >
            <span class="truncate">{{ tag.name }}</span>
            <button
              class="delete-btn opacity-0 hover:opacity-100 text-red-500 hover:text-red-700 transition-opacity absolute right-2"
              title="删除TAG"
              @click="deleteTag(tag.name, $event)"
            >
              <svg
                class="h-4 w-4"
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
                xmlns="http://www.w3.org/2000/svg"
              >
                <path d="M6 18L18 6M6 6l12 12" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" />
              </svg>
            </button>
          </div>
        </div>
      </div>
    </div>
    <div class="flex flex-col flex-1 h-full pr-2 pb-2 box-border overflow-hidden">
      <div class="flex flex-row items-center justify-between pl-2 h-[56px] flex-shrink-0">
        <span class="text-xl font-bold">{{ tagStore.currentTagName || '请选择TAG' }}</span>
        <el-button circle class="!mr-4" @click="settingsDialogVisible = true">
          <div class="i-fluent:settings-32-regular" />
        </el-button>
      </div>
      <div class="flex-1 flex flex-col bg-white rounded-xl px-2 overflow-hidden">
        <div class="flex flex-row mt-4 pl-2 flex-shrink-0">
          <el-button @click="addFile">添加文件</el-button>
          <el-button @click="updateAllStatus">刷新状态</el-button>
          <el-button @click="commitAndTag">提交&TAG</el-button>
          <el-button @click="exportList">清单导出</el-button>
        </div>
        <div v-if="!tagStore.currentTagName" class="mt-8 text-center text-gray-500">请先选择或创建TAG</div>
        <div v-else class="custom-table-container flex-1 mt-3">
          <table class="custom-table w-full border-collapse">
            <thead>
              <tr class="table-row">
                <th class="selection-column w-[30px] pt-2 pb-2 font-bold">
                  <el-checkbox v-model="isAllSelected" :indeterminate="isIndeterminate" @change="toggleSelectAll" />
                </th>
                <th
                  class="sortable-column min-w-[200px] pt-2 pb-2 font-bold cursor-pointer"
                  @click="sortByColumn('name')"
                >
                  文件名
                  <span v-if="sortColumn === 'name'" class="sort-icon">{{ sortDirection === 'asc' ? '▲' : '▼' }}</span>
                </th>
                <th class="w-[100px] pt-2 pb-2">
                  <div class="flex flex-row items-center">
                    状态
                    <div
                      class="ml-1 i-fluent:arrow-clockwise-16-regular h-4 w-4"
                      @click="() => tagStore.updateAllFilesStatus()"
                    />
                  </div>
                </th>
                <th class="w-[80px] pt-2 pb-2 font-bold">版本</th>
                <th class="w-[160px] pt-2 pb-2 font-bold">操作</th>
              </tr>
            </thead>
            <tbody>
              <template v-if="sortedFiles.length > 0">
                <tr
                  v-for="row in sortedFiles"
                  :key="row.path"
                  :class="{ 'selected-row': isRowSelected(row) }"
                  class="table-row"
                >
                  <td>
                    <el-checkbox v-model="row.selected" @change="toggleRowSelection(row)" />
                  </td>
                  <td class="truncate">{{ row.name }}</td>
                  <td>
                    <div v-if="row.rawStatus === 'loading'" class="tag">Loading</div>
                    <div v-else-if="row.rawStatus === CVSStatus.UpToDate" class="tag tag-primary">
                      {{ row.status }}
                    </div>
                    <div v-else class="tag tag-danger">{{ row.status }}</div>
                  </td>
                  <td>
                    <div class="flex flex-row select-none">
                      <div>{{ row.workingVersion }}</div>
                      <div v-if="row.workingVersion !== row.repositoryVersion" class="text-sm text-red-500 ml-1">
                        New
                      </div>
                    </div>
                  </td>
                  <td>
                    <div class="flex flex-row items-center">
                      <el-button class="!p-0" link type="primary" @click="openFile(row)">打开</el-button>
                      <el-button class="!p-0 ml-3" link type="primary" @click="removeFile(row)">删除</el-button>
                      <el-dropdown class="ml-3" trigger="click">
                        <el-button class="!p-0" link type="primary">
                          更多
                          <el-icon>
                            <ArrowDownBold class="!h-[10px] !w-[10px]" />
                          </el-icon>
                        </el-button>
                        <template #dropdown>
                          <el-dropdown-menu class="!px-2">
                            <el-dropdown-item @click="openFolder(row)" class="!px-3">打开文件夹</el-dropdown-item>
                            <el-dropdown-item
                              v-if="row.rawStatus !== CVSStatus.UpToDate"
                              @click="commitAndTagSingle(row)"
                              class="!px-3 !rounded"
                            >
                              提交&TAG
                            </el-dropdown-item>
                            <el-dropdown-item @click="exportListSingle(row)" class="!px-3 !mt-1 !rounded">
                              清单导出
                            </el-dropdown-item>
                            <el-dropdown-item
                              class="!px-3 !mt-1 !rounded"
                              v-if="row.baseVersionTag"
                              @click="openDiffPage(row)"
                            >
                              基线比对
                            </el-dropdown-item>
                          </el-dropdown-menu>
                        </template>
                      </el-dropdown>
                    </div>
                  </td>
                </tr>
              </template>
            </tbody>
          </table>
          <div v-if="sortedFiles.length === 0" class="flex flex-col items-center justify-center table-divider">
            <p class="text-gray-500 my-8">拖拽导入cvs文件</p>
          </div>
        </div>
      </div>
    </div>
  </div>
  <el-dialog v-model="historyDialogVisible" class="!w-[80%] !max-w-[80%]" destroy-on-close>
    <template #header>
      <span class="text-lg font-bold">{{ `${tagStore.currentTagName}提交清单` }}</span>
    </template>
    <pre class="py-2 overflow-y-auto">{{ histories }}</pre>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="copyHistory">复制到剪切板</el-button>
        <el-button type="primary" @click="historyDialogVisible = false">关闭</el-button>
      </div>
    </template>
  </el-dialog>
  <settings-dialog v-model:visible="settingsDialogVisible" />
</template>

<style>
.button-add-tag {
  @apply shadow;
  background-color: #528df4 !important;
}

.tag-selected {
  background-color: rgba(15, 122, 245, 0.2);
  border-left: 3px solid #409eff;
}

.tag-entry:not(.tag-selected):hover {
  background-color: rgba(15, 122, 245, 0.08);
}

.custom-table-container {
  position: relative;
  height: 100%;
  overflow-y: auto;
}

.custom-table {
  border-collapse: separate;
  border-spacing: 0;
  width: 100%;
  table-layout: fixed;
}

.custom-table th,
.custom-table td {
  text-align: left;
  padding: 6px 12px;
  border-bottom: 1px solid #ebeef5;
}

.table-divider {
  border-bottom: 1px solid #ebeef5;
}

.custom-table th {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: bold;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  position: sticky;
  top: 0;
  z-index: 2;
}

.custom-table td.truncate {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.custom-table tr:hover {
  background-color: #f5f7fa;
}

.selected-row {
  background-color: #ecf5ff;
}

.sortable-column {
  cursor: pointer;
  user-select: none;
}

.sort-icon {
  margin-left: 4px;
  font-size: 12px;
}
</style>
